import { useState } from 'react';
import { Card, Col, message, Row, Button } from 'antd';
import { PageContainer, ProForm, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { saveKnowledge } from '@/services/knowledge';

import useDetailType from '@/hooks/useDetailType';

import styles from './style.less';
interface Props {
  name?: string;
}

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 },
};

const KnowledgeDetail: React.FC<Props> = () => {
  const { goBack } = useDetailType<Record<'id', string | undefined>>();
  const [saveLoading, setSaveLoading] = useState(false);

  // 新增
  const onFinish = async (value: API.KnowledgeDetail) => {
    setSaveLoading(true);
    const res = await saveKnowledge(value);
    if (!res.code && res.data) {
      message.success('保存成功');
      goBack();
      setSaveLoading(false);
    }
  };

  return (
    <PageContainer>
      <div>
        <Card
          title={
            <h3>
              <ArrowLeftOutlined className={styles['title-icon']} onClick={goBack} />
              新增知识库
            </h3>
          }
        >
          <div>
            <ProForm<API.KnowledgeListItem>
              {...formItemLayout}
              layout="horizontal"
              submitter={{
                render: () => {
                  return (
                    <Row>
                      <Col span={14} offset={4}>
                        <Button onClick={goBack} className={styles['space-btn']}>
                          取消
                        </Button>
                        <Button
                          key="submit"
                          htmlType="submit"
                          className={styles['space-btn']}
                          type="primary"
                          loading={saveLoading}
                        >
                          创建
                        </Button>
                      </Col>
                    </Row>
                  );
                },
              }}
              // @ts-ignore
              onFinish={onFinish}
            >
              <ProFormText
                width="md"
                name="name"
                label="知识库名称"
                placeholder="最多20字符"
                fieldProps={{ maxLength: 20 }}
                rules={[
                  {
                    required: true,
                    message: '请输入名称',
                  },
                  {
                    max: 20,
                    message: '名称长度1-20个字符',
                  },
                ]}
              />
              <ProFormTextArea
                width="md"
                name="description"
                label="描述"
                placeholder="最多30字符"
                fieldProps={{ maxLength: 30 }}
              />
            </ProForm>
          </div>
        </Card>
      </div>
    </PageContainer>
  );
};

export default KnowledgeDetail;
